const { createCanvas, loadImage } = require('canvas')
const fs = require('fs')
const path = require('path')
const redis = require('./redis')
const utils = require('./util')

function main () {
  // 随机读取一张图片
  const imageList = utils.getDirImages('./images')
  const randomIndex = Math.random() * imageList.length | 0
  const imagePath = path.join('./images', imageList[randomIndex])

  const canvasWidth = 800
  const canvasHeight = 800

  // 随机生成一个角度
  const deg = (Math.random() * (330 - 30 + 1) + 30) | 0

  // 随机生成key
  const redisKey = 'SD' + Date.now()
  const canvas = createCanvas(canvasWidth, canvasHeight)
  const ctx = canvas.getContext('2d')

  ctx.arc(canvasWidth / 2, canvasHeight / 2, canvasWidth / 2, 0, Math.PI * 2, false);

  ctx.clip()

  return new Promise((resolve, reject) => {
    // Draw cat with lime helmet
    loadImage(imagePath).then((image) => {
      ctx.translate(canvasWidth / 2, canvasHeight / 2)
      ctx.rotate(deg * Math.PI / 180)
      ctx.drawImage(image, -canvasWidth / 2, -canvasWidth / 2, canvasWidth, canvasHeight)

      // 读取当前的template.html文件内容，并把image数据替换进去
      // 再生成index.html
      let templateContent = fs.readFileSync('./template.html', 'utf-8')
      templateContent = templateContent.replace(/\$\$/, canvas.toDataURL())
      fs.writeFileSync('./index.html', templateContent)

      const setResult = redis.syncSet(redisKey, deg)
      if (!setResult) {
        console.log('set redis error')
        return
      }
      resolve({
        imageData: canvas.toDataURL(),
        id: redisKey
      })
    })
  })
}

module.exports = main
